import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/hide_scroll_shadow/hide_scroll_shadow.dart';
import 'package:flutter_application_1/components/lose_focus/lose_focus.dart';
import 'package:flutter_application_1/global.dart';
import 'package:flutter_application_1/models/LocationPoi.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:flutter_application_1/provider/location_provider.dart';

import 'components/select_location_search_row.dart';

class SelectLocation extends StatefulWidget {
  @override
  _SelectLocationState createState() => _SelectLocationState();
}

class _SelectLocationState extends State<SelectLocation> {
  late LocationProvider _locationProvider;

  final Color primaryColor = Global.Primary_Color;

  final ScrollController _scrollController = ScrollController();

  // 滚动到顶部
  void _goTop() {
    _scrollController.jumpTo(0);
  }

  // 选择定位
  void _onSelected(dynamic obj) {
    if (obj is LocationPoi && obj.location != null) {
      List<String> locationList = obj.location!.split(',');
      double longitude = double.parse(locationList[0]);
      double latitude = double.parse(locationList[1]);
      _locationProvider.getLocation(longitude: longitude, latitude: latitude);
      _locationProvider.getAroundPois();
      _goTop();
    } else if (obj is LocationProvider) {}
    LoseFocus.loseFocus();
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      // 获取当前定位
      _locationProvider.getLocation();
      _locationProvider.getAroundPois();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('选择定位'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: primaryColor,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () {
              Fluttertoast.showToast(msg: '添加收货地址');
            },
          ),
        ],
      ),
      body: Consumer<LocationProvider>(
        builder: (BuildContext context, LocationProvider locationProvider,
            Widget? child) {
          _locationProvider = locationProvider;
          return WillPopScope(
            onWillPop: () async {
              locationProvider.clearSearchPois();
              return locationProvider.searchPois.length == 0;
            },
            child: LoseFocus(
              child: Stack(
                children: [
                  HideScrollShadow(
                    child: CustomScrollView(
                      controller: _scrollController,
                      slivers: [
                        // 搜索框
                        SelectLocationSearchRow(
                          primaryColor: primaryColor,
                          onChanged: (String keywords) {
                            if (keywords.isNotEmpty) {
                              locationProvider.search(keywords: keywords);
                            } else {
                              locationProvider.clearSearchPois();
                            }
                          },
                        ),

                        // 当前地址
                        SelectTitle(
                          title: '当前地址',
                        ),
                        SelectRow(
                          title: Builder(
                            builder: (BuildContext context) {
                              String text = '';
                              if (locationProvider.hasPermission) {
                                text = locationProvider.address != null &&
                                        locationProvider.address!.isNotEmpty
                                    ? locationProvider.address!
                                    : '定位中...';
                              } else {
                                text = '无定位权限';
                              }
                              return Text(
                                text,
                                style: TextStyle(
                                  color: primaryColor,
                                ),
                              );
                            },
                          ),
                          onTap: () {
                            _onSelected(locationProvider);
                          },
                          trailing: GestureDetector(
                            onTap: () {
                              locationProvider.setAddress('');
                              _locationProvider.fetchLocation(context);
                              _locationProvider.getAroundPois();
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                vertical: 3,
                                horizontal: 5,
                              ),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  color: primaryColor,
                                  width: 1,
                                ),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(3)),
                              ),
                              child: Text(
                                '重新定位',
                                style: TextStyle(
                                  height: 1,
                                  fontSize: 12,
                                  color: primaryColor,
                                ),
                              ),
                            ),
                          ),
                        ),

                        // 收货地址
                        SelectTitle(
                          title: '收货地址',
                        ),
                        SelectRow(
                          title: RichText(
                            text: TextSpan(
                              children: <InlineSpan>[
                                // 标签
                                WidgetSpan(
                                  child: Container(
                                    padding: EdgeInsets.only(
                                        top: 3, bottom: 2, left: 3, right: 3),
                                    margin: EdgeInsets.only(right: 5),
                                    decoration: BoxDecoration(
                                      border: Border.all(
                                        color: primaryColor,
                                      ),
                                    ),
                                    child: Text(
                                      '默认',
                                      style: TextStyle(
                                        height: 1,
                                        color: primaryColor,
                                        fontSize: 10,
                                      ),
                                    ),
                                  ),
                                ),
                                TextSpan(
                                  text: '广东省广州市天河区吉珠大道15号超级大夏超级大楼18楼703',
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          subtitle: Text(
                            '小明   13128269543',
                            style: TextStyle(
                              fontSize: 13,
                            ),
                          ),
                          onTap: () {
                            // _onSelected();
                            Fluttertoast.showToast(msg: '选择收货地址');
                          },
                        ),

                        // 附近地址
                        locationProvider.aroundPois.length > 0
                            ? SelectTitle(
                                title: '附近地址',
                              )
                            : SliverToBoxAdapter(),
                        ...List.generate(
                          locationProvider.aroundPois.length,
                          (index) {
                            LocationPoi poi =
                                locationProvider.aroundPois[index];
                            return SelectRow(
                              title: Text(poi.name ?? '未知地点'),
                              onTap: () {
                                _onSelected(poi);
                              },
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                  locationProvider.searchPois.length > 0
                      ? Positioned(
                          top: kToolbarHeight,
                          bottom: 0,
                          left: 0,
                          right: 0,
                          child: Container(
                            color: Colors.white,
                            child: CustomScrollView(
                              slivers: List.generate(
                                locationProvider.searchPois.length,
                                (index) {
                                  LocationPoi poi =
                                      locationProvider.searchPois[index];
                                  return SelectRow(
                                    title: Text(poi.name ?? '未知地点'),
                                    subtitle: Text(
                                        '${poi.pname}${poi.cityname}${poi.adname}${poi.address}'),
                                    onTap: () {
                                      _onSelected(poi);
                                      locationProvider.clearSearchPois();
                                    },
                                  );
                                },
                              ),
                            ),
                          ),
                        )
                      : SizedBox(),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

class SelectTitle extends StatelessWidget {
  final String title;

  SelectTitle({
    required this.title,
  });

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        color: Color.fromRGBO(235, 236, 238, 1),
        padding: EdgeInsets.all(10),
        child: Text(
          title,
          style: TextStyle(
            color: Color.fromRGBO(170, 170, 170, 1),
          ),
        ),
      ),
    );
  }
}

class SelectRow extends StatelessWidget {
  final Widget title;
  final Function onTap;
  final Widget? trailing;
  final Widget? subtitle;

  SelectRow({
    required this.title,
    required this.onTap,
    this.trailing,
    this.subtitle,
  });

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Column(
        children: <Widget>[
          ListTile(
            title: DefaultTextStyle(
              child: title,
              style: TextStyle(
                fontSize: 14,
                color: Colors.black,
              ),
            ),
            trailing: trailing,
            subtitle: subtitle,
            onTap: () {
              if (onTap != null) {
                onTap();
              }
            },
          ),
          Divider(
            height: 1,
            thickness: 1,
            color: Color.fromRGBO(235, 236, 238, 1),
          ),
        ],
      ),
    );
  }
}
